<script setup>
import * as api from "@/api/v-sys-service/exam/question";

const emits = defineEmits([
  'query',
  'update:modelValue'
])

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => {}
  }
})

const optionTags = ref([
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'
])

const formData = ref({
  id: '',//
  groupId: '',//归属分组
  questionType: '',//题目类别 1单选 2多选 3判断
  questionContent: '',//题目内容
  questionScore: 0,//题目分值
  answerAnalysis: '',//答案解析
  answerOptions: [
    {
      id: '',
      queId: '',
      optionTag: 'A',
      isRightAnswer: false,
      answer: '',
    },
    {
      id: '',
      queId: '',
      optionTag: 'B',
      isRightAnswer: false,
      answer: '',
    },
    {
      id: '',
      queId: '',
      optionTag: 'C',
      isRightAnswer: false,
      answer: '',
    },
    {
      id: '',
      queId: '',
      optionTag: 'D',
      isRightAnswer: false,
      answer: '',
    }
  ]
})

const saveBtnLoading = ref(false)
const formRef = ref()
const checkData = (rule, value, callback) => {
  if (value) {
    if (/[\u4E00-\u9FA5]/g.test(value)) {
      callback(new Error('编码不能输入汉字!'));
    } else {
      callback();
    }
  }
  callback();
}

const rules = ref({
  accessKey: [
    { validator: checkData, trigger: 'change' },
    { required: true, message: "请输入AccessKey ID", trigger: "blur" }
  ],
  questionType: [
    { required: true, message: "请选择题目类型", trigger: "change" },
  ],
  questionContent: [
    { required: true, message: "请填写题目内容", trigger: "blur" },
  ],
})
const visible = computed(
    {
      get(){
        return props.modelValue
      },
      set(val){
        emits('update:modelValue',val)
      }
    }
)

const title = computed(
    () => {
      return props.rowData && props.rowData.id ? '编辑' : '新增'
    }
)
watch(
    props.rowData,
    (val) =>{
      if (val && val.id) {
        const form = formData.value
        const answerOptions = form.answerOptions
        Object.assign(form,val)
        if (form.answerOptions) {
          form.answerOptions.forEach((item, index) => item.optionTag = optionTags.value[index])
        }else {
          form.answerOptions = answerOptions
        }
      }
      if (val.groupId) formData.value.groupId = val.groupId
    },
    {
      immediate: true,
    }
)
onMounted(()=>{
  init()
})
const init = () => {
  init_Cache()
}
const init_Cache = () => {

}

const addAnswer = () => {
  const form = formData.value
  if (form.answerOptions.length < optionTags.value.length - 1) {
    form.answerOptions.push({
      id: '',
      queId: '',
      optionTag: optionTags.value[form.answerOptions.length],
      isRightAnswer: false,
      answer: '',
    })
  } else {
    ElMessage.error(`最多只能添加${optionTags.value.length - 1}个选项`)
  }
}

const delAnswer = () => {
  const form = formData.value
  form.answerOptions.length > 2 ? form.answerOptions.pop() : ElMessage.error(`最少需要2个选项`)
}
const sure = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const form = formData.value
      if (!form.answerOptions.find(e => e.isRightAnswer)) {
        ElMessage.error(`请选择正确答案`)
        return
      }
      if (form.answerOptions.find(e => e.answer.trim() === '')) {
        ElMessage.error(`请填写选项内容`)
        return
      }
      if ((form.questionType == 1 || form.questionType == 3) && form.answerOptions.filter(ele => ele.isRightAnswer).length > 1) {
        ElMessage.error(`单选题、判断题是只能选择一个正确答案`)
        return
      }
      saveBtnLoading.value = true
      const { code } = await api.save(formData.value)
      saveBtnLoading.value = false
      if (code === 200){
        visible.value = false
        ElMessage({message: '保存成功', type: 'success',})
        emits('query')
      }
    }
  })
}
</script>

<template>
  <v-dialog v-model="visible" width="60%" :loading="saveBtnLoading" :title="title" @sure="sure">
    <el-form ref="formRef" :model="formData" :rules="rules">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="题目类别：" prop="questionType">
            <v-select-dict v-model="formData.questionType" type-code="QuestionType" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="题目分值：" prop="questionScore">
            <el-input-number
                placeholder="请填写分数"
                :min="1" :max="10"
                style="width: 100%"
                v-model="formData.questionScore">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="题目内容：" prop="questionContent">
            <el-input v-model="formData.questionContent" type="textarea" show-word-limit
                      :autosize="{ minRows: 3, maxRows: 5}" maxlength="500"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="&ensp;答案解析：&nbsp;" prop="answerAnalysis">
            <el-input v-model="formData.answerAnalysis" type="textarea" show-word-limit
                      :autosize="{ minRows: 2, maxRows: 5}" maxlength="500"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="elDividerBox">
        <span class="line"></span>
        <el-button type="primary" circle plain size="small" @click="addAnswer">
          <template #icon><i-ep-plus /></template>
        </el-button>
        <span class="text">增加/删除选项</span>
          <el-button type="danger" circle plain size="small" @click="delAnswer">
            <template #icon><i-ep-minus /></template>
          </el-button>
        <span class="line"></span>
      </div>
<!--      <div class="flex justify-center" style="margin-bottom: 10px">
        <div class="flex justify-center">
          <el-button type="primary" circle plain size="small" @click="addAnswer">
            <template #icon><i-ep-plus /></template>
          </el-button>
          <el-button type="danger" circle plain size="small" @click="delAnswer">
            <template #icon><i-ep-minus /></template>
          </el-button>
        </div>
      </div>-->
      <el-form-item
          v-for="(item, index) in formData.answerOptions"
          :key="index"
          :label="'\u2002选项'+ item.optionTag"
          :prop="item.answer"
      >
        <div class="flex flex-sub">
          <el-checkbox v-model="item.isRightAnswer"></el-checkbox>
          {{'\u2003\u2002'}}
          <el-input
              type="textarea"
              placeholder="请输入选项内容"
              v-model="item.answer"
              :autosize="{ minRows: 2, maxRows: 4 }"
          ></el-input>
        </div>
      </el-form-item>
    </el-form>
  </v-dialog>
</template>

<style scoped lang="scss">
.el-select {
  width: 100%;
}
.elDividerBox {
  .line {
    width: calc(50% - 55px);
  }

  .text {
    width: 150px;
    text-align: center;
  }
}
</style>
